package test.day01;

public class AddTwoNumbers {
	// 2 个逆序的链表，要求从低位开始相加，得出结果也逆序输出，返回值是逆序结果链表的头结点。
	// 极限情况包含进位
	// Input: (9 -> 9 -> 9 -> 9 -> 9) + (1 -> )
	// Output: 0 -> 0 -> 0 -> 0 -> 0 -> 1
	// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
	// Output: 7 -> 0 -> 8
	// Explanation: 342 + 465 = 807.

	public static void main(String[] args) {
		ListNode first0 = new ListNode(2);
		ListNode first1 = new ListNode(4);
		ListNode first2 = new ListNode(3);
		first0.next = first1;
		first1.next = first2;

		ListNode second0 = new ListNode(5);
		ListNode second1 = new ListNode(6);
		ListNode second2 = new ListNode(4);
		second0.next = second1;
		second1.next = second2;

		System.out.println(addTwoNumbers(first0, second0));
	}

	public static int addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode dummyHead = new ListNode(0);
		ListNode p = l1, q = l2, curr = dummyHead;
		int carry = 0;
		while (p != null || q != null) {
			int x = (p != null) ? p.val : 0;
			int y = (q != null) ? q.val : 0;
			int sum = carry + x + y;
			carry = sum / 10;
			curr.next = new ListNode(sum % 10);
			curr = curr.next;
			if (p != null) {
				p = p.next;
			}
			if (q != null) {
				q = q.next;
			}
		}
		if (carry > 0) {
			curr.next = new ListNode(carry);
		}
		return dummyHead.next.val;
	}

	static class ListNode{
		int val;
		ListNode next;
		ListNode(int x){
			val = x;
		}
	}
}
